//
//  ViewController.swift
//  TableViewSwift
//
//  Created by lisonglin on 14/04/2017.
//  Copyright © 2017 lisonglin. All rights reserved.
//

import UIKit
import Alamofire
class ViewController: UIViewController {

    let dataSource:NSMutableArray = []
    
        lazy var tableView: UITableView = {
            let tableView = UITableView.init(frame: self.view.frame, style: UITableView.Style.plain)
            tableView.tableFooterView = UIView()
            tableView.delegate = self;
            tableView.dataSource = self;

            return tableView
        }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.title = "TableView"
        
        for _ in 1...20 {
            
            dataSource.add(arc4random_uniform(100))
        }
        let searchItem = UIBarButtonItem.init(title: "search", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.searchAction(sender:)))
        
        self.navigationItem.leftBarButtonItems = [searchItem]
        //导航栏右侧添加 添加 编辑 按钮
        let addItem = UIBarButtonItem.init(title: "+", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.addBtnClick(sender:)))
        let editItem = UIBarButtonItem.init(title: "edit", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.editBtnClick))
        
        self.navigationItem.rightBarButtonItems = [addItem,editItem]
        
        
        self.view .addSubview(tableView)
       //接口地址
               let urls:String = "http://api.map.baidu.com/telematics/v3/weather"
               //参数
               let parameters:Dictionary = ["location":"嘉兴","output":"json","ak":"5slgyqGDENN7Sy7pw29IUvrZ"]
               //Alamofire 请求实例
               AF.request(URL(string: urls)!, method: .post, parameters: parameters)
                               .responseString { (responses) in
                   let ste:String = responses.value ?? ""
                   print(ste)
               }
//        AF.request(urls,method: .get,parameters: parameters).responseJSON { response in
//         //print(response.result)
//
//            switch response.result {
//                case .success(let JSON):
//                    print("Success with JSON: \(JSON)")
//                    let dict = JSON as! Dictionary<String,AnyObject>
//
//                    let message = dict["message"] as! String
//                    print(message)
//                case .failure(let error):
//                    print("Request failed with error: \(error)")
//         }
//
//    }
        PPNetworkHelper.requestData(.get, URLString: urls,parameters: parameters) { (response) in
            print(response)
           
        }
        
    }
    @objc func searchAction(sender:UIButton){
        
        let searchView = SearchResultVC(self.view)
        self.present(searchView, animated: true) {
            print("rtyuiop");
        }
    }
    //右侧添加按钮
    @objc func addBtnClick(sender:UIButton) {
        //添加一个在最前面

        self.dataSource.insert(arc4random_uniform(100), at: 0)

        let index = IndexPath.init(row: 0, section: 0)

        self.tableView.insertRows(at: [index], with: UITableView.RowAnimation.fade)
    }

    //右侧编辑按钮
    @objc func editBtnClick() {
        if self.tableView.isEditing == false {
            self.tableView.setEditing(true, animated: true)
        }else{
            self.tableView.setEditing(false, animated: true)
        }
    }


    
}

extension ViewController:UITableViewDelegate{
        //点击
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            tableView .deselectRow(at: indexPath, animated: true)
//            let vc = testViewController()
            let vc = TestTableview()

    //        vc.text = "\(self.dataSource[indexPath.row])"

            self.navigationController?.pushViewController(vc, animated: true)

        }
}
extension ViewController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        注册cell示例
        //        tableView.ts_registerCellNib(UITableViewCell.self)
        //        获取循环利用的cell示例
        //        let cell = tableView.ts_dequeueReusableCell(UITableViewCell.self)
        
        let cellId = "cellId"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellId)

        if (cell == nil) {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: cellId)
        }

        cell?.textLabel?.text = "\(self.dataSource[indexPath.row])"

        return cell!
    }
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
           return true
       }

       func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

           if sourceIndexPath != destinationIndexPath {
               //获取移动的值
               let itemValue = self.dataSource[sourceIndexPath.row]

               //删除移动的值
               self.dataSource.removeObject(at: sourceIndexPath.row)

               //如果移动的区域大于现有行数 拼在最后面
               if destinationIndexPath.row > self.dataSource.count {
                   self.dataSource.add(itemValue)
               }else{
                   self.dataSource.insert(itemValue, at: destinationIndexPath.row)
               }


           }
       }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == UITableViewCell.EditingStyle.delete {

            //删除数据源当前的数据
            self.dataSource .removeObject(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.fade)
        }
    }
}

